﻿using AL.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AL
{
    public partial class FormAddPublicAccount : Form
    {
        public FormAddPublicAccount()
        {
            InitializeComponent();
        }



        private void FormAddPublicAccount_Load(object sender, EventArgs e)
        {
            // 绑定类别数据
            comboBox_ClassName.Items.Clear();
            //comboBox_ClassName.Items.Add("根目录");

            var categories = CacheHolder.GetCategories();
            foreach (var category in categories)
            {
                comboBox_ClassName.Items.Add(category);
            }
            
        }



        // 添加公众号处理
        private void btn_AddAccount_Click(object sender, EventArgs e)
        {
            var opendId = txt_OpenId.Text;
            
            // 过滤掉多余字符串
            opendId = opendId.Replace("openid=", "");

            if (string.IsNullOrWhiteSpace(opendId))
            {
                MessageBox.Show(@"请输入一个公众帐号的 OpenId");
            }
            else
            {
                // 根据搜索网址获取一个公众账号的数据
                var sogoAccountAnylizer = new SogoAccountAnalizer();
                var account = sogoAccountAnylizer.GetAccount(string.Format("http://weixin.sogou.com/gzh?openid={0}", opendId));
            
                // TODO: 添加公众帐号到本地数据缓存中
                if (account == null || string.IsNullOrWhiteSpace(account.OpenId) || string.IsNullOrWhiteSpace(account.Name))
                {
                    MessageBox.Show(@"公众号不存在");
                }
                else
                {
                    var className = comboBox_ClassName.Text;
                    if (!string.IsNullOrWhiteSpace(className) && className != "根目录") account.ClassName = className;

                    var act = DAL.PublicAccount.Provider.GetByOpenId(opendId);
                    if (act != null && act.OpenId.Length > 0)
                    {
                        MessageBox.Show(@"已存在的公众号");
                    }
                    else
                    {
                        CacheHolder.AddAccount(account);
                        MessageBox.Show(@"公众号保存成功");

                        this.Hide();
                        this.DialogResult = DialogResult.OK;
                    }
                }
            }
        }

    }
}
